package com.zw.blog.exception.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 可以在错误页面输出信息，不用在服务器查看日志
 */
@ControllerAdvice //拦截所有@Controller
public class ExceptionControllerHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)//表示异常处理方法
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {

        //记录request url和异常信息
        logger.error("Request URL: {}, Exception: {}", request.getRequestURL(), e);

        //指定了ResponseStatus, 就让Springboot自行处理
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error"); //返回到哪个页面
        return mv;
    }
}
